package com.vcg.comment.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.vcg.comment.dao.CommentDao;
import com.vcg.comment.model.Comment;
import com.vcg.comment.model.CommentProperty;
import com.vcg.comment.model.query.CommentExample;
import com.vcg.comment.service.CommentPropertyService;
import com.vcg.comment.service.CommentService;
import com.vcg.comment.support.clean.FilterComment;
import com.vcg.comment.support.clean.data.YunCleanJsonData;
import com.vcg.comment.support.data.CommentResult;
import com.vcg.comment.utils.TimeUtil;
import com.vcg.common.base.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentServiceImpl extends BaseServiceImpl<Comment, CommentExample, String> implements CommentService {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private FilterComment filterComment;

    @Autowired
    private CommentPropertyService commentPropertyService;

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());


    @RequestMapping("/getById")
    public Comment getById(String id) {
        Comment comment = commentDao.selectByPrimaryKey(id);
        return comment;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JSONObject addComment(Comment comment) {
        if (comment == null
                || StringUtils.isBlank(comment.getResourceId())
                || StringUtils.isBlank(comment.getMessage())
                || StringUtils.isBlank(comment.getUserId())) {
            return new CommentResult()
                    .setStatus(1101)
                    .setMsg("参数不符合规则,请检查必填项目!")
                    .setTimestamp(new Date())
                    .toJSONObject();
        }


        logger.info(comment.toString() + " " + commentPropertyService);
        CommentProperty commentProperty = commentPropertyService.getById(comment.getResourceId());
        if (commentProperty != null) {
            if (commentProperty.getIsCloseComment() != null && commentProperty.getIsCloseComment() == 1) {
                return new CommentResult()
                        .setStatus(1013)
                        .setMsg("用户关闭了评论!")
                        .toJSONObject();
            }
        }

        //由于YunClean 最大只支持32位Id, 故截取resourceId 后12位+当前时间戳 为唯一id.
        long createDate = new Date().getTime();
        String id = comment.getResourceId().substring(20)
                + "_" + TimeUtil.getReverseTime(createDate).substring(5)
                + "_" + RandomUtils.nextInt(1000, 9999);
        YunCleanJsonData yunCleanJsonData = new YunCleanJsonData();
        yunCleanJsonData.setId(id);
        yunCleanJsonData.addContent("text", comment.getMessage(), 1);
        if (!filterComment.doFilter(yunCleanJsonData)) {
            return new CommentResult()
                    .setStatus(1102)
                    .setMsg("评论违规!")
                    .setTimestamp(new Date())
                    .toJSONObject();
        }

        comment.setId(id)
                .setCreateDate(createDate);
        if (StringUtils.isBlank(comment.getParentId())) {
            comment.setParentId("0");
        }

        commentDao.insert(comment);

        if (commentProperty != null) {
            commentProperty = new CommentProperty()
                    .setCommentCount(commentProperty.getCommentCount() + 1)
                    .setResourceId(comment.getResourceId());
            commentPropertyService.updateByPrimaryKey(commentProperty);
        } else {
            commentProperty = new CommentProperty()
                    .setCommentCount(0)
                    .setResourceId(comment.getResourceId());
            commentPropertyService.insertSelective(commentProperty);
        }


        return new CommentResult()
                .setStatus(200)
                .setMsg("评论成功!")
                .setTimestamp(new Date())
                .toJSONObject();
    }

    @RequestMapping(value = "/del")
    public JSONObject delComment(String id) {
        CommentExample query = new CommentExample();
        query.or(query.createCriteria().andIdEqualTo(id));
        query.or(query.createCriteria().andParentIdEqualTo(id));
        int commentCount = commentDao.deleteByExample(query);
        return new CommentResult()
                .setStatus(200)
                .setMsg("删除成功!")
                .setCommentCount(commentCount)
                .toJSONObject();
    }


    @RequestMapping(value = "/getComment")
    public JSONObject getComment(String resourceId, @RequestParam(defaultValue = "0") Integer startNum, @RequestParam(defaultValue = "10") Integer endNum) {
        if (StringUtils.isBlank(resourceId)) {
            return new CommentResult()
                    .setStatus(1101)
                    .setMsg("参数不能为空!")
                    .toJSONObject();
        }
        CommentProperty commentProperty = commentPropertyService.getById(resourceId);
        if (commentProperty != null) {
            if (commentProperty.getIsCloseComment() != null && commentProperty.getIsCloseComment() == 1) {
                return new CommentResult()
                        .setStatus(1013)
                        .setMsg("用户关闭了评论!")
                        .toJSONObject();
            }
        }

        CommentExample query = new CommentExample();
        query.createCriteria()
                .andResourceIdEqualTo(resourceId)
                .andParentIdEqualTo("0");
        query.setOrderByClause("create_date desc");
        query.setLimit(Arrays.asList(startNum, endNum));
        List<Comment> parentComments = commentDao.selectByExample(query);

        //根据父评论 查询所有子评论,由于评论只显示两级,故只for循环遍历一次 ,如有多级,可采用递归查询
        for (Comment parentComment : parentComments) {
            query.clear();
            query.createCriteria()
                    .andParentIdEqualTo(parentComment.getId());
            query.setOrderByClause("create_date");
            List<Comment> childComments = commentDao.selectByExample(query);
            parentComment.setChildComments(childComments);
        }
        query.clear();
        query.createCriteria().andResourceIdEqualTo(resourceId);
        int count = commentDao.countByExample(query);
        return new CommentResult()
                .setStatus(200)
                .setTimestamp(new Date())
                .setComments(parentComments)
                .setCommentCount(count)
                .toJSONObject();
    }

    @RequestMapping("/closeComment")
    public JSONObject closeComment(String resourceId) {
        CommentProperty commentProperty = new CommentProperty();
        commentProperty.setResourceId(resourceId)
                .setIsCloseComment(1);
        commentPropertyService.updateByPrimaryKey(commentProperty);
        return new CommentResult()
                .setMsg("评论关闭成功")
                .setStatus(200)
                .setTimestamp(new Date())
                .toJSONObject();
    }

    @RequestMapping("/openComment")
    public JSONObject openComment(String resourceId) {
        CommentProperty commentProperty = new CommentProperty();
        commentProperty.setResourceId(resourceId)
                .setIsCloseComment(0);
        commentPropertyService.updateByPrimaryKey(commentProperty);
        return new CommentResult()
                .setMsg("评论开启成功")
                .setStatus(200)
                .setTimestamp(new Date())
                .toJSONObject();
    }


    @Override
    public void setDao() {
        this.baseDao = commentDao;
    }

}